/*
 * CHESSFABRIK.COM
 * Developer: Azer Koçulu <http://azer.kodfabrik.com>
 * 2008-09-18
 */
var
main = {},
Chess = pi.base.extend({
  "$Init":function(){
    this.environment.setServer([]);
    for(var i=0, len=servers.length; i<len; i++){
      var server = servers[i],
      instance = new Server(i, server.url);
      this.environment.getServer().push(instance);
      if(server.master){
        this.environment.setMasterServer(instance);
      }
    };
    this.environment._setActiveServer(this.environment.getServer()[0]);
    pi.util.AddEvent(window,"resize",this.event.resize.curry(this.event));
  },
  "changeLanguage":function(){
    document.location.href = "/"+this.element.getLanguageCombobox().element.value;
  },
  "createMainScreen":function(){
    this.element.setContainer(new pi.element("div"));
    //this.element.setHeader(new pi.element("div").attribute.addClass("Header").update(main.text.name.toUpperCase()).insert(this.element.getContainer()));
    this.element.setMiddle(new pi.element("div").attribute.addClass("Middle").insert(this.element.getContainer()));
    this.element.setFooter(new pi.element("div").attribute.addClass("Footer").child.add(
      new pi.element("h2").attribute.addClass("Title").update(main.text.about),
      new pi.element("div").update('\
      %(footer).<br />\
      %(links): <a href="http://multiplayerchess.googlecode.com">%(projectPage)</a> <a href="http://code.google.com/p/multiplayerchess/issues/list">%(bugReport)</a> <a href="http://code.google.com/p/multiplayerchess/source/browse/#svn/trunk">%(browseSource)</a><br />\
      <div class="Donation"><form action="https://www.paypal.com/cgi-bin/webscr" method="post"><input type="hidden" name="cmd" value="_s-xclick">\
      <input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----MIIHHgYJKoZIhvcNAQcEoIIHDzCCBwsCAQExggEwMIIBLAIBADCBlDCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20CAQAwDQYJKoZIhvcNAQEBBQAEgYBFhTW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KAK93E5XCPIA=-----END PKCS7-----">\
      <input type="image" src="https://www.paypal.com/en_GB/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="">\
      <img alt="" border="0" src="https://www.paypal.com/tr_TR/i/scr/pixel.gif" width="1" height="1">\
      </form></div>\
      '.format({ 
        footer:main.text.footer, 
        links:main.text.links, 
        projectPage:main.text.projectPage, 
        bugReport:main.text.bugReport,
        browseSource:main.text.browseSource
      }).replace("Kodfabrik","<a href='http://azer.kodfabrik.com'>Azer Ko&#231;ulu</a>"))
    ).insert(new pi.element("div").attribute.addClass("FooterContainer").insert(this.element.getContainer())));
    
    this.element.setNicknameInput(new pi.element("input").attribute.addClass("Nickname").update( Request.filter(this.environment.getUser().environment.getName()) ));
    this.element.getNicknameInput().event.addListener("keyup",Request.inputController.curry(window,this.element.getNicknameInput().element));
    this.element.setLocationInput(new pi.element("input").attribute.addClass("Location").update( Request.filter(this.environment.getUser().environment.getLocation()) ));
    this.element.getLocationInput().event.addListener("keyup",Request.inputController.curry(window,this.element.getLocationInput().element));
    
    this.element.setGameForm(new pi.element("div").attribute.addClass("GameForm").child.add( new pi.element("h2").attribute.addClass("Title").update(main.text.join) ));
    this.element.setServerPicker( new pi.element("div").attribute.addClass("ServerSet").child.add( new pi.element("h3").update(main.text.servers) ).insert( new pi.element("div").attribute.addClass("ServerSetContainer").insert(this.element.getGameForm()) )  );
    this.element.setTablePicker( new pi.element("div").attribute.addClass("TableSet").child.add(new pi.element("h3").update(main.text.tables) ).insert( new pi.element("div").attribute.addClass("TableSetContainer").insert(this.element.getGameForm()) ) );
    this.element.getGameForm().child.add(new pi.element("div").attribute.addClass("Clean"));
    
    this.element.setLanguageCombobox(new pi.element("select").attribute.addClass("LanguageCombobox"));
    this.element.getLanguageCombobox().event.addListener("change",this.changeLanguage.curry(this));
    for(var key in this.environment.getLanguage()){
      var el = new pi.element("option").attribute.set("value",key).update(
        this.environment.getLanguage()[key]
      );
      
      if(this.environment.getDefaultLanguage()==key)
        el.attribute.set("selected",true);
        
      this.element.getLanguageCombobox().child.add(
        el
      );
    }

    this.element.setServerListbox(new pi.element("div").attribute.addClass("ServerList").insert( this.element.getServerPicker() ));
    for(var i=0,len=this.environment.getServer().length; i<len; i++){
      var server = this.environment.getServer()[i];
      server.environment.setElement(
        new pi.element("a").attribute.addClass("ServerButton"+(((!this.environment.getActiveServer()&i==0)||this.environment.getActiveServer()==server)&&" ServerButtonSelected"||"")).event.addListener(
          "click",
          this.environment.setActiveServer.curry(this.environment,server)
        ).insert(this.element.getServerListbox())
      );
      server.update();
    };
  
    this.element.getTablePicker().child.add(
      new pi.element("a").event.addListener("click",this.createTable.curry(this)).attribute.addClass("NewGameButton").child.add(
      new pi.element("span").update(main.text.newGame)
      ),
      new pi.element("label").attribute.addClass("Directive").update(main.text.tableListDirective)
    );
    
    this.element.setTableList( new pi.element("div").attribute.addClass("TableList").insert(this.element.getTablePicker()) );
    this.element.getTableList().child.add(
      new pi.element("div").attribute.addClass("Row").child.add(
        new pi.element("div").attribute.addClass("Column Wide").update(main.text.player),
        new pi.element("div").attribute.addClass("Column Wide").update(main.text.location),
        new pi.element("div").attribute.addClass("Clean")
      )
    );
   
    this.element.getTableList().child.add(
      this.element.setTableListContent(new pi.element("div").attribute.addClass("TableListContent")).element.getTableListContent(),
      this.element.setServerInfoBox(new pi.element("div").attribute.addClass("ServerInfoBox").update(main.text.initializing)).element.getServerInfoBox()
    );
    
    this.element.getMiddle().child.add(
      new pi.element("div").attribute.addClass("ProfileSettings").child.add(
        new pi.element("div").attribute.addClass("Border").child.add(
          new pi.element("div").attribute.addClass("Left").child.add(
            new pi.element("h2").attribute.addClass("Title").update(main.text.setProfile),
            new pi.element("label").update(main.text.nickname+": "),
            this.element.getNicknameInput().update(this.environment.getUser().environment.getName()),
            new pi.element("label").update(main.text.location+": "),
            this.element.getLocationInput().update(this.environment.getUser().environment.getLocation())
          ),
          new pi.element("div").attribute.addClass("Right").child.add(
            new pi.element("h2").attribute.addClass("Title").update(main.text.language),
            this.element.getLanguageCombobox()
          ),
          new pi.element("div").attribute.addClass("Clean")
        )
      ),
      new pi.element("div").attribute.addClass("GameFormContainer").child.add(this.element.getGameForm())
    );
    
    this.event.resize();
    setTimeout(this.event.resize.curry(this.event),50);
    setTimeout(this.event.resize.curry(this.event),250);
    setTimeout(this.event.resize.curry(this.event),1000);
  },
  "createTable":function(){
    this.environment.setTable(new Table());
    this.environment.getTable().environment.setUser(
      new User().environment.setColor(0)
    );
    this.environment.getActiveServer().create();
  },
  "join":function(_tableId){
    this.environment.setTable(new Table(Table.REVERSE));
    this.environment.getTable().environment.setUser(
      new User().environment.setColor(1)
    );
    this.environment.getActiveServer().join(_tableId);
    return this;
  },
  "environment":{
    "_language":null,
    "_defaultLanguage":"",
    "_activeServer":null, "_masterServer":null, "_server":null, "_table":null , "_user":null,
    "setActiveServer":function(_server){
      if(this.getActiveServer()){
        this.getActiveServer().disconnect();
        this.getActiveServer().environment.getElement().attribute.removeClass("ServerButtonSelected");
      };
      
      this._setActiveServer( _server );
      if(this.getActiveServer().environment.getElement()){
        this.getActiveServer().environment.getElement().attribute.addClass("ServerButtonSelected");
      }
      this._parent_.element.getTableListContent().update("");
      this.getActiveServer().listen.table();
    }
  },
  "element":{
    "_colorComboBox":null, "_container":null, "_gameForm":null, "_header":null, "_languageCombobox":null, "_locationInput":null, "_middle":null, "_nicknameInput":null, "_profileButton":null, "_serverInfoBox":null, "_serverListbox":null, "_serverPicker":null, "_tableList":null, "_tableListContent":null, "_tablePicker":null, "_footer":null,
    "setContainer":function(_el){
      _el.attribute.addClass("Container").insert(document.body);
      this._setContainer(_el);
    }
  },
  "event":{
    "readTableList":function(_data){
      console.log(",,, tablelist response has been sent.processing...","data length:",_data.length);
      this._parent_.element.getTableListContent().update("");
      for(var i=0, len=_data.length; i<len; i++){
        var game = _data[i];
        console.log(",,,, creating new table row ",game.id);
        this._parent_.element.getTableListContent().child.add(
          new pi.element("div").event.addListener("click",this._parent_.join.curry(this._parent_,game.id)).attribute.addClass("Row").child.add(
            new pi.element("div").attribute.addClass("Column Wide").update(game.player.name),
            new pi.element("div").attribute.addClass("Column Wide").update(game.player.location),
            new pi.element("div").attribute.addClass("Column Wide").update(game.id+"/"+(this._parent_.environment.getActiveServer().environment.getTime()-game.time)),
            new pi.element("div").attribute.addClass("Clean")
          )
        );
      };
      console.log(",,, done.");
      setTimeout(this._parent_.environment.getActiveServer().listen.table.curry(this._parent_.environment.getActiveServer().listen),2500);
    },
    "resize":function(_event){
      var vp = pi.util.GetViewport(), el = this._parent_.element.getContainer();
      el.addStyle({
        "left":( Math.max(10,parseInt(vp.width/2)-parseInt(el.element.offsetWidth/2) ))+"px",
        "top":( Math.max(10,parseInt(vp.height/2)-parseInt(el.element.offsetHeight/2) ))+"px"
      });
    }
  }
});
